package demo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Server {

	public static String IP = "localhost";
	public static int PORT = 8888;

	private Map<String,Socket> socketMap= new HashMap<String, Socket>();
	
	private ServerSocket serverSocket;
	
	public void startup() {
		try {
			serverSocket = new ServerSocket(PORT);
			new Thread(new AcceptRequest()).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private class AcceptRequest implements Runnable{

		public void run() {
			try {
				while (true){
				Socket	socket = serverSocket.accept();
					DataInputStream dataInputStream=new DataInputStream(socket.getInputStream());
					String clientName = dataInputStream.readUTF();
					socketMap.put(clientName,socket);
				new Thread(new ReceiveMessage(socket)).start();
				System.out.println("Comes Online..");}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private class ReceiveMessage implements Runnable{
     private Socket socket;
		public ReceiveMessage(Socket socket){
			this.socket = socket;
		}
		public void run() {
			DataInputStream dataInputStream= null;
			try {
				dataInputStream = new DataInputStream(socket.getInputStream());
				String message = "";
				while (true){
				message = dataInputStream.readUTF();

					if(message.contains("@ALL")){
						Collection<Socket> collection= socketMap.values();
						Iterator<Socket> iterator = collection.iterator();
						while (iterator.hasNext()){
							Socket socket =iterator.next();
							DataOutputStream dataOutputStream=new DataOutputStream(socket.getOutputStream());
							dataOutputStream.writeUTF(message);
						}

					}


				System.out.println(message);}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}


	public static void main(String[] args) {
		Server server = new Server();
		server.startup();
	}
	
	
	
	
}
